import { createDistStru } from './city.js';
import { TransportBlock } from './transport.js';

// 游戏类，管理所有游戏对象
class Game {
    constructor() {
        this.allCity = []; // 所有城市
        this.allTransBlock = []; // 所有交通区块
    }

    // 对所有城市进行排序，计算城市间距离
    sortAllCity() {
        const size = this.allCity.length;
        const length = size % 2 === 0 ? size / 2 : Math.floor(size / 2) + 1;

        for (let i = 0; i < length; i++) {
            for (let j = i + 1; j < size; j++) {
                const c1 = this.allCity[i];
                const c2 = this.allCity[j];
                // 等级越高相当于距离越小
                const d = c1.getDist(c2) + c1.level + c2.level;
                c1.allDist.push(createDistStru(d, c2));
                c2.allDist.push(createDistStru(d, c1));
            }
        }

        // 按距离排序
        for (const c of this.allCity) {
            c.allDist.sort((d1, d2) => d1.dist - d2.dist);
        }
    }

    // 更新所有交通区块
    updateTransBlock() {
        // 创建一个新的数组来存储未完成的交通区块
        const remainingTransBlocks = [];
        
        for (let i = 0; i < this.allTransBlock.length; i++) {
            const item = this.allTransBlock[i];
            if (item.update()) {
                // 运输完成，这里可以添加回调处理
                // 由于JavaScript中不需要手动内存管理，所以不需要delete
            } else {
                // 运输未完成，保留
                remainingTransBlocks.push(item);
            }
        }
        
        // 更新交通区块列表
        this.allTransBlock = remainingTransBlocks;
    }

    // 添加交通区块
    addTransBlock(starting, destination, livingMaterial = 0, protectiveMaterial = 0,
        medicalMaterial = 0, newsNum = 0, medicalNum = 0, securityNum = 0, trafficNum = 0,
        researchNum = 0) {
        
        // 检查并添加物资和人员
        const judgeAdd = (property, amount) => {
            if (amount <= starting[property][typeof starting[property].material !== 'undefined' ? 'material' : 'workable']) {
                b[property] = amount;
                starting[property][typeof starting[property].material !== 'undefined' ? 'sub' : 'sub'](amount);
                return true;
            } else {
                return false;
            }
        };

        const b = new TransportBlock(starting, destination);
        
        // 依次检查并添加各项物资和人员
        if (!judgeAdd('livingMaterial', livingMaterial)) return false;
        if (!judgeAdd('protectiveMaterial', protectiveMaterial)) return false;
        if (!judgeAdd('medicalMaterial', medicalMaterial)) return false;
        if (!judgeAdd('newsNum', newsNum)) return false;
        if (!judgeAdd('medicalNum', medicalNum)) return false;
        if (!judgeAdd('securityNum', securityNum)) return false;
        if (!judgeAdd('trafficNum', trafficNum)) return false;
        if (!judgeAdd('researchNum', researchNum)) return false;
        
        // 所有检查通过，添加到列表
        this.allTransBlock.push(b);
        return true;
    }
}

// 创建一个游戏实例
const game = new Game();

export { Game, game };
